package com.sj.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sj.common.dto.role.SetRoleMenuParam;
import com.sj.common.lang.ApiResult;
import com.sj.common.lang.Const;
import com.sj.common.lang.RedisConst;
import com.sj.entity.Role;
import com.sj.entity.SysRoleMenu;
import com.sj.entity.UserRole;
import com.sj.interceptor.AuthCheck;
import com.sj.service.RoleService;
import com.sj.service.SysMenuService;
import com.sj.service.SysRoleMenuService;
import com.sj.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 孙峻
 * @since 2022-03-09
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色模块")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private UserRoleService userRoleService;

    @DeleteMapping("/del/{roleId}")
    @AuthCheck
    @ApiOperation("删除角色信息")
    public ApiResult delRole(@PathVariable Integer roleId) {
        Long count = userRoleService.lambdaQuery().eq(UserRole::getRoleId, roleId).count();
        if (count > 0) {
            return ApiResult.error("有用户拥有该角色，不能被删除");
        }
        sysRoleMenuService.remove(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, roleId));
        boolean result = roleService.removeById(roleId);
        if (result) {
            return ApiResult.success("删除成功");
        }
        return ApiResult.error("删除失败");
    }

    @PutMapping("/save")
    @ApiOperation("保存角色信息")
    @AuthCheck
    public ApiResult addRole(@RequestBody Role role) {
        boolean result = roleService.saveOrUpdate(role);
        if (result) {
            return ApiResult.success("保存成功");
        }
        return ApiResult.error("保存失败");
    }

    @PutMapping("/set/menu")
    @ApiOperation("给角色分配权限接口")
    @AuthCheck
    @CacheEvict(cacheNames = {"menu-list"}, keyGenerator = RedisConst.REDIS_SJ_KEY_GENERATOR, allEntries = true)
    public ApiResult setRoleMenu(@RequestBody SetRoleMenuParam setRoleMenuParam) {
        // 删除该角色所有菜单
        sysRoleMenuService.remove(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, setRoleMenuParam.getRoleId()));
        // 重新添加
        List<SysRoleMenu> collect = Arrays.asList(setRoleMenuParam.getMenuIds()).stream().map(item -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(setRoleMenuParam.getRoleId());
            sysRoleMenu.setMenuId(item);
            return sysRoleMenu;
        }).collect(Collectors.toList());
        boolean result = true;
        if (setRoleMenuParam.getMenuIds().length != 0) {
            result = sysRoleMenuService.saveBatch(collect);
        }
        if (result) {
            return ApiResult.success("设置成功");
        }
        return ApiResult.error("设置失败");
    }

    @GetMapping("/list")
    @ApiOperation("获取角色列表")
    @AuthCheck
    public ApiResult getRoleList(@RequestParam(required = false) Integer current,
                                 @RequestParam(required = false) Integer size,
                                 @RequestParam(required = false, defaultValue = "") String name,
                                 @RequestParam(required = false) String type) {
        if (current != null && size != null && Const.ROLE_PAGE.equals(type)) {
            IPage<Role> page = new Page<>(current, size);
            return ApiResult.success(roleService.lambdaQuery().like(Role::getName, name).page(page));
        }
        return ApiResult.success(roleService.lambdaQuery().like(Role::getName, name).list());
    }

}
